import { Context, Next } from 'koa';
import { logger } from '../utils/logger';

interface AppError extends Error {
  status?: number;
}

export async function errorHandler(ctx: Context, next: Next) {
  try {
    await next();
  } catch (err) {
    const error = err as AppError;
    logger.error('Error handling request: ', error);
    
    ctx.status = error.status || 500;
    ctx.body = {
      status: 'error',
      message: error.message || 'Internal server error',
      ...(process.env.NODE_ENV === 'development' && { stack: error.stack }),
    };
  }
}
